"""
配置验证器
Configuration Validator
"""
import os
import logging
from pathlib import Path
from typing import List, Dict, Any
from .settings import settings


class ConfigValidator:
    """配置验证器"""
    
    def __init__(self):
        self.errors: List[str] = []
        self.warnings: List[str] = []
    
    def validate_all(self) -> Dict[str, Any]:
        """验证所有配置"""
        self.errors.clear()
        self.warnings.clear()
        
        # 验证基础配置
        self._validate_basic_config()
        
        # 验证目录配置
        self._validate_directories()
        
        # 验证数据库配置
        self._validate_database_config()
        
        # 验证WVP配置
        self._validate_wvp_config()
        
        # 验证AI配置
        self._validate_ai_config()
        
        return {
            "valid": len(self.errors) == 0,
            "errors": self.errors,
            "warnings": self.warnings
        }
    
    def _validate_basic_config(self):
        """验证基础配置"""
        if not settings.APP_NAME:
            self.errors.append("APP_NAME不能为空")
        
        if not settings.VERSION:
            self.errors.append("VERSION不能为空")
        
        if settings.PORT < 1 or settings.PORT > 65535:
            self.errors.append("PORT必须在1-65535范围内")
        
        if not settings.SECRET_KEY or settings.SECRET_KEY == "your-secret-key-change-in-production":
            self.warnings.append("建议更改默认的SECRET_KEY")
    
    def _validate_directories(self):
        """验证目录配置"""
        directories = [
            ("DATA_DIR", settings.DATA_DIR),
            ("LOGS_DIR", settings.LOGS_DIR),
            ("UPLOAD_DIR", settings.UPLOAD_DIR),
            ("AI_MODEL_PATH", settings.AI_MODEL_PATH)
        ]
        
        for name, path in directories:
            try:
                Path(path).mkdir(parents=True, exist_ok=True)
            except Exception as e:
                self.errors.append(f"无法创建目录 {name}: {path} - {e}")
    
    def _validate_database_config(self):
        """验证数据库配置"""
        if not settings.DATABASE_URL:
            self.errors.append("DATABASE_URL不能为空")
        
        # 如果是SQLite，检查目录是否可写
        if settings.DATABASE_URL.startswith("sqlite:///"):
            db_path = settings.DATABASE_URL.replace("sqlite:///", "")
            db_dir = Path(db_path).parent
            if not db_dir.exists():
                try:
                    db_dir.mkdir(parents=True, exist_ok=True)
                except Exception as e:
                    self.errors.append(f"无法创建数据库目录: {e}")
    
    def _validate_wvp_config(self):
        """验证WVP配置"""
        if not settings.WVP_BASE_URL:
            self.warnings.append("WVP_BASE_URL未配置，WVP功能将不可用")
        
        if not settings.WVP_API_KEY and not (settings.WVP_USERNAME and settings.WVP_PASSWORD):
            self.warnings.append("WVP认证信息未配置（API_KEY或用户名密码）")
    
    def _validate_ai_config(self):
        """验证AI配置"""
        if settings.AI_MAX_WORKERS < 1:
            self.errors.append("AI_MAX_WORKERS必须大于0")
        
        if settings.AI_TIMEOUT <= 0:
            self.errors.append("AI_TIMEOUT必须大于0")
        
        # 检查AI模型目录
        model_path = Path(settings.AI_MODEL_PATH)
        if not model_path.exists():
            try:
                model_path.mkdir(parents=True, exist_ok=True)
                self.warnings.append(f"AI模型目录不存在，已创建: {settings.AI_MODEL_PATH}")
            except Exception as e:
                self.warnings.append(f"无法创建AI模型目录: {e}")


def validate_config() -> Dict[str, Any]:
    """验证配置的便捷函数"""
    validator = ConfigValidator()
    return validator.validate_all()


if __name__ == "__main__":
    # 运行配置验证
    result = validate_config()
    
    if result["valid"]:
        print("✅ 配置验证通过")
    else:
        print("❌ 配置验证失败")
        for error in result["errors"]:
            print(f"  错误: {error}")
    
    if result["warnings"]:
        print("⚠️  配置警告:")
        for warning in result["warnings"]:
            print(f"  警告: {warning}")